package com.example.oop.Service;

import com.example.oop.ChatRoom.ChatRoomManager;
import com.example.oop.ServerOperation.NetOperation.NetConnection;
import com.example.oop.ServerOperation.NetOperation.NetPacket;
import com.example.oop.POJO.ChatRoom;
import org.json.JSONException;
import org.json.JSONObject;

//将 Connection 交给 ServiceHandler 来完全负责
public class ServiceHandler extends Thread {
    NetConnection connection;  //前后端连接
    ChatRoom chatRoom;  // 当前聊天室

    public ServiceHandler(NetConnection connection) {
        this.connection = connection;
    }

    @Override
    public void run() {
        // 反空闲：规定最大空闲30s
        connection.setSoTimeout(1000 * 30);

        //长连接方式，一个用户创建一个线程，该线程始终可以接受创建线程的用户的请求
        while (true) {
            try {
                //接受请求如果阻塞时间过程会抛出异常
                NetPacket requestPkt = connection.receive();  //接受请求
                if (requestPkt != null) {
                    String request = requestPkt.toString("UTF-8");  //获取字符串类型请求体

                    /* 根据不同的的请求，作出相应的应答 */
                    String response = handleRequest(request);
                    connection.send((short) 0, response);

                    JSONObject jsonReq = new JSONObject(request);
                    String cmd = jsonReq.optString("cmd").trim();  //获取命令码
                    if (cmd.equals("register")) break;
                }
            } catch (Exception e) {
                // 打印Connection reset（无用信息）
//                e.printStackTrace();
                break;
            }
        }

        connection.close();  //关闭连接

        // 注销会话
        if (chatRoom != null) {
            ChatRoomManager.i.deleteChatRoom(chatRoom.getId());
            System.out.println("用户 " + chatRoom.getUsername() + " 已断开\n");
        }
    }

    private String handleRequest(String request) throws JSONException {
//        System.out.println(1);
        JSONObject jsonReq = new JSONObject(request);
        String cmd = jsonReq.optString("cmd").trim();  //获取命令码
        JSONObject args = null;
        if (jsonReq.has("args")) {
            args = jsonReq.getJSONObject("args");
//            System.out.println(args);
        }

        // jsonResponse应答
        JSONObject jsonResp = new JSONObject();
        if (cmd.equals("register")) {  //注册

            RegisterService registerService = new RegisterService();
            if (args != null) {
                jsonResp = registerService.doRegister(args);
            }

        } else if (cmd.equals("login")) {  //登陆

            LoginService loginService = new LoginService();
            if (args != null) {
                jsonResp = loginService.doLogin(args);
            }

        } else if (cmd.equals("logout")) {  //登出

            LogoutService logoutService = new LogoutService();
            if (args != null) {
                jsonResp = logoutService.doLogout(args);
            }

        } else if (cmd.equals("sendMessage")) {  //发送消息

            ChatService chat = new ChatService();
            if (args != null) {
                jsonResp = chat.doSend(args);
            }

        } else if (cmd.equals("getMessage")) {  //获取聊天室消息

            ChatService chat = new ChatService();
            if (args != null) {
                jsonResp = chat.doGet(args);
            }

        } else if (cmd.equals("ready")) {  //用户准备开始对局

            ReadyService readyService = new ReadyService();
            if (args != null) {
                jsonResp = readyService.ready(args);
            }

        } else if (cmd.equals("doPlay")) {   //用户落子

            PlayService playService = new PlayService();
            if (args != null) {
                jsonResp = playService.doPlay(args);
            }

        } else if (cmd.equals("getPlayStatus")) {  //获取对局状态信息

            PlayService playService = new PlayService();
            if (args != null) {
                jsonResp = playService.getPlayStatus(args);
            }

        } else if (cmd.equals("concede")) {  //用户认输

            PlayService playService = new PlayService();
            if (args != null) {
                jsonResp = playService.doConcede(args);
            }

        } else if (cmd.equals("win")) {  //用户认输

            PlayService playService = new PlayService();
            if (args != null) {
                jsonResp = playService.doWin(args);
            }

        } else {
            jsonResp.put("status", -1);
            jsonResp.put("reason", "不支持的命令类型: " + cmd);
        }

        return jsonResp.toString(2);
    }
}
